#    Copyright 2010 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildCompanySetupForm(company):
    from django.contrib import admin
    Dict={}
    CompanyChoices=[]
    if(company):
        CompanyChoices.append([company.id, company.Name[:30]])
    CompanyChoices.append((-1, 'None Selected'))
    Companies=Company.objects.all().order_by('Name')
    for i in Companies:
        if(not [i.id, str(i.Name)[:30]] in CompanyChoices):
            CompanyChoices.append([i.id, str(i.Name)[:30]])
    Dict['CompanySelection']=forms.ChoiceField(CompanyChoices, required=False)
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['PoleTreatmentIndicator']=forms.BooleanField(required=False)
    Dict['PoleJointUseIndicator']=forms.BooleanField(required=False)
    Dict['ManufacturerIndicator']=forms.BooleanField(required=False)
    Dict['VegetationManagementIndicator']=forms.BooleanField(required=False)
    Dict['ContractorIndicator']=forms.BooleanField(required=False)
    Dict['GroundRodTestIndicator']=forms.BooleanField(required=False)
    Dict['Companyid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict


def ProcessCompanySetupForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    PoleTreatmentIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PoleTreatmentIndicator')
    PoleJointUseIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PoleJointUseIndicator')
    ManufacturerIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ManufacturerIndicator')
    ContractorIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ContractorIndicator')
    GroundRodTestIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'GroundRodTestIndicator')
    CompanySelectionid=COOPGIS_FormMisc.FormGetInteger(form, 'CompanySelection')
    try:
        company=Company.objects.filter(id=CompanySelectionid)[0]
    except:
        company=None
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateCompany', ObjectName=Name, Description=Description, PoleTreatmentIndicator=PoleTreatmentIndicator, 
                               PoleJointUseIndicator=PoleJointUseIndicator, ManufacturerIndicator=ManufacturerIndicator, ContractorIndicator=ContractorIndicator, GroundRodTestIndicator=GroundRodTestIndicator,
                               CommandUserName=UserName)
        company=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'Companyid')):
        Companyid=COOPGIS_FormMisc.FormGetInteger(form, 'Companyid')
        company=Company.objects.filter(id=Companyid)[0]
        Objectid, ObjectIndexWhenReverseSorted=company.GetCommandidData()
        command=command.Create(Name='EditCompany', ObjectName=Name, Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               Description=Description, PoleTreatmentIndicator=PoleTreatmentIndicator, PoleJointUseIndicator=PoleJointUseIndicator, GroundRodTestIndicator=GroundRodTestIndicator,
                               ManufacturerIndicator=ManufacturerIndicator, ContractorIndicator=ContractorIndicator,
                               CommandUserName=UserName)
        company=command.Process()
    return company

def PopulateCompanySetupForm(form, company):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(company):
        form.data['Name']=company.Name
        form.data['Companyid']=company.id
        form.data['Description']=company.Description
        form.data['PoleTreatmentIndicator']=company.PoleTreatmentIndicator
        form.data['PoleJointUseIndicator']=company.PoleJointUseIndicator
        form.data['ManufacturerIndicator']=company.ManufacturerIndicator
        form.data['ContractorIndicator']=company.ContractorIndicator
        form.data['GroundRodTestIndicator']=company.GroundRodTestIndicator
    else:
        form.data['Name']=''
        form.data['Companyid']=''
        form.data['Description']=''
        form.data['PoleTreatmentIndicator']=''
        form.data['PoleJointUseIndicator']=''
        form.data['ManufacturerIndicator']=''
        form.data['ContractorIndicator']=''
        form.data['GroundRodTestIndicator']=''
    return form




def BuildVoltageSetupForm(voltage):
    from django.contrib import admin
    Dict={}
    VoltageChoices=[]
    if(voltage):
        VoltageChoices.append([voltage.id, voltage.Name[:30]])
    VoltageChoices.append((-1, 'None Selected'))
    Voltages=Voltage.objects.all().order_by('Name')
    for i in Voltages:
        if(not [i.id, str(i.Name)[:30]] in VoltageChoices):
            VoltageChoices.append([i.id, str(i.Name)[:30]])
    Dict['VoltageSelection']=forms.ChoiceField(VoltageChoices, required=False)
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Value']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransmissionIndicator']=forms.BooleanField(required=False)
    Dict['PrimaryIndicator']=forms.BooleanField(required=False)
    Dict['SecondaryIndicator']=forms.BooleanField(required=False)
    Dict['ServiceIndicator']=forms.BooleanField(required=False)
    Dict['Voltageid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict

def ProcessVoltageSetupForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    Value=COOPGIS_FormMisc.FormGetFloat(form, 'Value')
    TransmissionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'TransmissionIndicator')
    PrimaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PrimaryIndicator')
    SecondaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SecondaryIndicator')
    ServiceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ServiceIndicator')
    Voltageid=COOPGIS_FormMisc.FormGetInteger(form, 'VoltageSelection')
    try:
        voltage=Voltage.objects.filter(id=Voltageid)[0]
    except:
        voltage=None
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateVoltage', ObjectName=Name, Description=Description, Value=Value, 
                               TransmissionIndicator=TransmissionIndicator, PrimaryIndicator=PrimaryIndicator,
                               SecondaryIndicator=SecondaryIndicator, ServiceIndicator=ServiceIndicator,
                               CommandUserName=UserName)
        voltage=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'Voltageid')):
        Voltageid=COOPGIS_FormMisc.FormGetInteger(form, 'Voltageid')
        voltage=Voltage.objects.filter(id=Voltageid)[0]
        Objectid, ObjectIndexWhenReverseSorted=voltage.GetCommandidData()
        command=command.Create(Name='EditVoltage', ObjectName=Name, Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               Description=Description, Value=Value, 
                               TransmissionIndicator=TransmissionIndicator, PrimaryIndicator=PrimaryIndicator,
                               SecondaryIndicator=SecondaryIndicator, ServiceIndicator=ServiceIndicator,
                               CommandUserName=UserName)
        voltage=command.Process()
    return voltage

def PopulateVoltageSetupForm(form, voltage):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(voltage):
        form.data['Name']=voltage.Name
        form.data['Voltageid']=voltage.id
        form.data['Description']=voltage.Description
        form.data['TransmissionIndicator']=voltage.TransmissionIndicator
        form.data['PrimaryIndicator']=voltage.PrimaryIndicator
        form.data['SecondaryIndicator']=voltage.SecondaryIndicator
        form.data['ServiceIndicator']=voltage.ServiceIndicator
    else:
        form.data['Name']=''
        form.data['Voltageid']=''
        form.data['Description']=''
        form.data['TransmissionIndicator']=False
        form.data['PrimaryIndicator']=False
        form.data['SecondaryIndicator']=False
        form.data['ServiceIndicator']=False
    return form

def BuildCompatibleUnitCategorizationForm():
    Dict={}
    CompatibleUnitChoices=[]
    for i in CompatibleUnit.objects.all().order_by('Name'):
        CompatibleUnitChoices.append([i.id, str(i.Name)[:30]])
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['CompatibleUnit']=forms.ChoiceField(CompatibleUnitChoices, required=False)
    Dict['PrimaryIndicator']=forms.BooleanField(required=False)
    Dict['SecondaryIndicator']=forms.BooleanField(required=False)
    Dict['ServiceIndicator']=forms.BooleanField(required=False)
    Dict['EditedAssemblyCount']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    return Dict
    
def ProcessCompatibleUnitCategorizationForm(form, UserName):
    CompatibleUnit = COOPGIS_FormMisc.FormGetObjectFromid(form, 'CompatibleUnit', djangoproject.models.compatibleunit.CompatibleUnit)
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    PrimaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PrimaryIndicator')
    SecondaryIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SecondaryIndicator')
    ServiceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ServiceIndicator')
    if not CompatibleUnit or not UpdateIndicator:
        return None, None
    Assemblies = list(Assembly.objects.filter(CompatibleUnit=CompatibleUnit).exclude(PrimaryIndicator=True).exclude(SecondaryIndicator=True).exclude(ServiceIndicator=True))
    if PrimaryIndicator:
        Primary=True
        Secondary=False
        Service=False
    elif SecondaryIndicator:
        Primary=False
        Secondary=True
        Service=False
    elif ServiceIndicator:   
        Primary=False
        Secondary=False
        Service=True
    for i in Assemblies:
            if i.MeterForm:
                meterFormName = i.MeterForm.Name
            else:
                meterFormName = None
            if i.MeterServiceType:
                meterServiceTypeName = i.MeterServiceType.Name
            else:
                meterServiceTypeName = None
            if i.TransformerBank:
                transformerBankid = i.TransformerBank.id
            else:
                transformerBankid = -1
            if i.StakerWorkOrder:
                stakerWorkOrderid = i.StakerWorkOrder.id
            else:
                stakerWorkOrderid = -1
            command=Command()
            command=command.Create(Name='EditAssembly', Assemblyid=i.id, AssemblyName=i.CompatibleUnit.Name,  
                             TagNumber=i.TagNumber, PutIntoServiceDate=i.PutIntoServiceDate, 
                             PrimaryIndicator=Primary, SecondaryIndicator=Secondary, ServiceIndicator=Service, 
                             BypassIndicator=i.BypassIndicator, PoleStubIndicator=i.PoleStubIndicator,             
                             PoleLightIndicator=i.PoleLightIndicator, PoleGuyIndicator=i.PoleGuyIndicator,
                             PoleMeterIndicator=i.PoleMeterIndicator, OwnerName=i.AssemblyOwner, ManufacturerName=i.Manufacturer, 
                             MeterFormName=meterFormName, OpenIndicator=i.OpenIndicator,  Rotation=i.Rotation,
                             MeterOnPoleIndicator=i.MeterOnPoleIndicator, PhaseAIndicator=i.PhaseAIndicator, PhaseBIndicator=i.PhaseBIndicator,
                             PhaseCIndicator=i.PhaseCIndicator, PhaseNeutralIndicator=i.PhaseNeutralIndicator,
                             CircuitNumber=i.CircuitNumber, SerialNumber=i.SerialNumber, 
                             MeterNumber=i.MeterNumber, MeterDCSINumber=i.MeterDCSINumber, MapNumber=i.MapNumber, OldMapNumber=i.OldMapNumber,
                             MeterServiceTypeName=meterServiceTypeName, CommandUserName=UserName,
                             PhysicalAddress=i.PhysicalAddress, IdleIndicator=i.IdleIndicator, InstallStatus=i.InstallStatus.Name,
                             #fudge reverse index until removal
                             StakerWorkOrderid=stakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=-1,
                             StakerRecipeNumber=i.StakerRecipeNumber, 
                             #fudge reverse index until removal
                             TransformerBankid=transformerBankid, TransformerBankIndexWhenReverseSorted=-1)
            command.Process()
    return (CompatibleUnit, len(Assemblies))
    

def PopulateCompatibleUnitCategorizationForm(form, compatibleUnit, editCount):
    if(compatibleUnit):
        form.data['CompatibleUnit']=compatibleUnit.id
    else:
        form.data['CompatibleUnit']=-1 
    form.data['UpdateIndicator']=False
    form.data['PrimaryIndicator']=False
    form.data['SecondaryIndicator']=False
    form.data['ServiceIndicator']=False
    form.data['EditedAssemblyCount']=str(editCount)
    return form
